package com.deuwise.common.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;
import java.util.UUID;

/**
 * @author zhangjunyu
 */
public class FileUtil {
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }
    /**
     * 获取json文件
     * @param file
     * @return
     */
    public static StringBuilder getJsonStr(MultipartFile file){
        StringBuilder sb=new StringBuilder();

        try (InputStream inputStream =file.getInputStream()) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            sb = new StringBuilder();
            BufferedReader br = new BufferedReader(reader);
            Date time = new Date();
            String line;
            try {
                while ((line = br.readLine()) != null) {
                    // 一次读入一行数据
                    if (line != null && line != "") {
                        sb.append(line);
                    }
                }
                reader.close();
            } catch (IOException  e) {
                e.printStackTrace();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }catch (IOException ex){

        }
        return  sb;
    }
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    /**
     * 获取文件后缀名
     * @param fileName
     * @return
     */
    public static String getFileType(String fileName) {
        if(fileName!=null && fileName.indexOf(".")>=0) {
            return fileName.substring(fileName.lastIndexOf("."), fileName.length());
        }
        return "";
    }

    public static String renameToUUID(String fileName) {
        return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
    }
}
